package gui;

import gui.calendarview.DayViewPanel;
import gui.wizard.WizardStatus;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import no.ntnu.fp.model.Person;
import query.PersonQuery;

public class SelectUserDialog extends JDialog {
	
	private static final long serialVersionUID = 1L;
	
	public SelectUserDialog(Frame owner) {
		super(owner,"Velg burker", true);
		WizardStatus.setCompleted(false);
		add(new SelectUserPanel());
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		pack();
		setVisible(true);
	}
	
	private JDialog getDialog() {
		return this;
	}
	
	public void closeDialog() {
		setVisible(false);
		dispose();
	}
	
	private class SelectUserPanel extends JPanel {
		
		private static final long serialVersionUID = 1L;
		private JTextField input;
		private JButton ok, cancel;
		
		public SelectUserPanel() {
			input = new JTextField(20);
			ok = new JButton("OK");
			ok.addActionListener(new OkAction());
			cancel = new JButton("Avbryt");
			cancel.addActionListener(new CancelAction());
			
			JPanel buttonPanel = new JPanel();
			buttonPanel.add(ok);
			buttonPanel.add(cancel);
			
			setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
			add(input);
			add(buttonPanel);
		}
		
		private class OkAction implements ActionListener {
			public void actionPerformed(ActionEvent e) {
				String text = input.getText();
				for ( Person p : PersonQuery.getAllPeople() ) {
					if ( p.getName().equals(text) ) {
						JFrame frame = new JFrame(p.getName());
						DayViewPanel d = new DayViewPanel(CalendarWindow.getDate(), p);
						d.getList().setEnabled(false);
						frame.add(d);
						frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
						frame.pack();
						frame.setVisible(true);
						frame.requestFocus();
						closeDialog();
						return;
					}
				}
				JOptionPane.showMessageDialog(getDialog(), "Det finnes igen brukere med dette navnet");
			}
		}
		
		private class CancelAction implements ActionListener {
			public void actionPerformed(ActionEvent e) {
				closeDialog();
			}
		}
	}
}
